package com.js.data.system.controller;


import cn.hutool.core.io.FileUtil;
import com.js.data.common.api.CommonResult;
import com.js.data.common.constant.SymbolConstant;
import com.js.data.common.exception.ApiException;
import com.js.data.common.utils.RedisUtils;
import com.js.data.common.utils.StringUtils;
import com.js.data.system.annotation.Log;
import com.js.data.system.util.UserUtil;
import com.js.data.system.vo.UploadVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * FileController-文件上传
 *
 * @author wujj
 * @version 1.0.0
 * @since 2022/10/09 14:37
 */
@RestController
@RequestMapping("/sys")
public class FileController {
    @Value("${upload.file.path}")
    private String uploadPath;

    @Value("${upload.file.max-size}")
    private Long maxSize;
    @Value("${upload.file.view-prefix}")
    private String viewPrefix;
    @Resource
    private RedisUtils<String> redisUtil;
    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Log(value = "上传文件")
    @PostMapping("/file/upload/{module}")
    public CommonResult<UploadVO> uploadFile(@RequestParam("file") MultipartFile file, @PathVariable String module) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            throw new ApiException("文件不存在");
        }
        return CommonResult.success(uploadLocal(file, module), "上传文件成功");
    }

    /**
     * 本地文件上传
     *
     * @param multipartFile 文件
     */
    private UploadVO uploadLocal(MultipartFile multipartFile, String module) {
        // 参数检验
        if (multipartFile == null) {
            throw new ApiException("文件不能为空");
        }
        // 文件限制10M
        long size = multipartFile.getSize();
        if (size > maxSize*1024*1024) {
            throw new ApiException("length exceeds limit of "+maxSize+"M");
        }
        String folder = uploadPath + module + File.separator;
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        UploadVO uploadVO = new UploadVO();
        String suffix = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(), SymbolConstant.DOT);
        String fileName = UserUtil.getUserId() + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + SymbolConstant.DOT + suffix;
        String path = folder +  fileName;
        File file = new File(path);
        if (FileUtil.exist(file)) {
            throw new ApiException("文件已存在");
        }
        File file1;
        try {
            file1 = FileUtil.writeBytes(multipartFile.getBytes(), path);
        } catch (IOException e) {
            throw new ApiException("文件上传失败");
        }
        if (file1.length() < 0) {
            throw new ApiException("文件上传失败");
        }

        uploadVO.setFileName(multipartFile.getOriginalFilename());
        uploadVO.setSavePath(module + "/" + fileName);
        uploadVO.setSrcType(suffix);
        uploadVO.setViewPath(viewPrefix + module + "/" + fileName);
        return uploadVO;

    }
    /**
     * 设置文件路径
     * @param uuid uid
     * @param path 路径
     * @return 成功
     */
    @GetMapping(value = "/sign/set-file-path/{uuid}", produces = "application/json; charset=utf-8")
    public CommonResult<Boolean> setFilePath(@PathVariable String uuid,
                                             @RequestParam(name = "path") String path) {
        redisUtil.setValue("sign:" + uuid, path, 60L);
        return CommonResult.success();
    }

    /**
     * 获取文件路径
     * @param uuid uid
     * @return 路径
     */
    @GetMapping(value = "/sign/get-file-path/{uuid}", produces = "application/json; charset=utf-8")
    public CommonResult<String> getFilePath(@PathVariable String uuid) {
        return CommonResult.success(redisUtil.getValue("sign:" + uuid));
    }

    /**
     * 设置扫码成功
     *
     * @param uuid uuid
     * @return return
     */
    @GetMapping(value = "/sign/set-scan-code/{uuid}", produces = "application/json; charset=utf-8")
    public CommonResult<Boolean> setScanCode(@PathVariable String uuid) {
        redisUtil.setValue("sign-success:" + uuid, "1", 600L);
        return CommonResult.success();
    }

    /**
     * 扫码成功结果查询
     *
     * @param uuid uuid
     * @return return
     */
    @GetMapping(value = "/sign/get-scan-code/{uuid}", produces = "application/json; charset=utf-8")
    public CommonResult<Boolean> getScanCode(@PathVariable String uuid) {
        String value = redisUtil.getValue("sign-success:" + uuid);
        return CommonResult.success("1".equals(value));
    }

}
